package com.powerhua.core.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlUtil {

    static Logger logger = Logger.getLogger(XmlUtil.class);

    /**
     * 
     * @param filePath
     * @return
     */
    public static Document getDocument(String filePath) {
        Document dataDocument = DocumentHelper.createDocument();
        SAXReader rd = new SAXReader();
        try {
            File file = new File(filePath);
            dataDocument = rd.read(file);
        } catch (DocumentException de) {
            logger.error("Exception throw when get document. " + "\n=== File path: [" + filePath + "].",
                    de);
            return null;
        }
        return dataDocument;
    }

    /**
     * 
     * @return 1 - fail; 0 - succeed
     */
    public static int saveDocument(Document doc, String filePath) {
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(new FileOutputStream(filePath),
                    format);
            writer.write(doc);
            writer.close();
        } catch (IOException ioe) {
            logger.error(
                    "Exception throw when save document. " + "\n=== File path: " + filePath + ".",
                    ioe);
            return 1; // fail.
        }
        return 0; // succeed.
    }
}
